package com.example.restful.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.restful.common.BaseService;
import com.example.restful.common.MaterialState;
import com.example.restful.domain.Borrow;
import com.example.restful.domain.Material;
import com.example.restful.domain.Personnel;
import com.example.restful.mapper.BorrowMapper;
import com.example.restful.mapper.MaterialMapper;
import com.example.restful.mapper.PersonnelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class PersonnelService implements BaseService<Personnel> {

    @Autowired
    PersonnelMapper personnelMapper;
    @Autowired
    BorrowMapper borrowMapper;
    @Autowired
    MaterialMapper materialMapper;

    @Override
    public List<Personnel> selectAll() {
        return personnelMapper.selectList(null);
    }

    @Override
    public Personnel selectById(int id) {
        QueryWrapper<Personnel> wrapper = new QueryWrapper<>();
        wrapper.eq("id",id);
        return personnelMapper.selectOne(wrapper);
    }

    @Override
    public boolean addItem(Personnel item) {
        try{
            personnelMapper.insert(item);
        }catch (Exception e){
            return false;
        }

        return true;
    }

    @Override
    public boolean deleteById(int id) {
        // 删除实验室人员时，查找有没有借用材料未归还
        List<Borrow> borrowList = borrowMapper.selectList(new QueryWrapper<Borrow>().eq("personnel_id", id));
        //如果有未归还记录则删除失败
        for(Borrow borrow: borrowList){
            borrowMapper.deleteById(borrow);
            Material material = materialMapper.selectById(borrow.getPersonnelId());
            if(material.getState() == MaterialState.LOANED) {
                return false;
            }
        }
        // 一并删除借出记录
        for(Borrow borrow: borrowList){
            borrowMapper.deleteById(borrow);
        }
        return personnelMapper.deleteById(id) != 0;
    }

    public boolean updateById(int id,Personnel personnel){
        personnel.setId(id);
        int count = personnelMapper.updateById(personnel);
        return count != 0;
    }
}
